/*
 * @Autor: taobo
 * @Date: 2020-06-16 13:43:47
 * @LastEditTime: 2020-06-21 09:03:09
 * @Description: memcopy的实现
 */ 
#include <iostream>
#include <cstring>
using namespace std;
/* Copy N bytes of SRC to DEST.  
extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
		     size_t __n) __THROW __nonnull ((1, 2));
*/
void *memcpy(void *dest, const void *src, size_t n)
{
    if(dest == NULL || src == NULL || n<=0)
        return NULL;
    char *s_dest = static_cast<char*>(dest);
    const char *s_src = static_cast<const char*>(src);
    while(n--)
    {
        *(s_dest++) = *(s_src++);
    }
    return NULL;
}
/* Copy N bytes of SRC to DEST, guaranteeing
   correct behavior for overlapping strings.  
extern void *memmove (void *__dest, const void *__src, size_t __n)
     __THROW __nonnull ((1, 2));
*/
void *memove(void *dest, const void *src, size_t n)
{
    if(dest == NULL || src == NULL || n<=0)
        return NULL;
    char *s_dest = static_cast<char*>(dest);
    const char *s_src = static_cast<const char*>(src);
    if(s_dest > s_src && s_src + n > s_dest)
    {
        s_dest = s_dest + n -1;
        s_src = s_src + n - 1;
        while (n--)
        {
            *(s_dest--) = *(s_src--);
        }
    }else
    {
        while (n--)
        {
            *(s_dest++) = *(s_src++);
        }
        
    }
    return NULL;
}

int main()
{
    char p[] = "12345";
    char q[] = "67890";
    memcpy(p,q,5);
    //cout << &p <<" "<< &q <<"\n";
    //cout << p <<" "<< q <<"\n";
    char s[] = "12345678";
    char v[9] = "\0";
    //cout << sizeof(v) << " " << sizeof(s) << endl;//9 9
    //cout << strlen(v) << " " << strlen(s) << endl;//0 8
    memove(v,s,8);
    cout << v << " " << s << endl;
    return 0;
}